﻿using LibBinary.DataSource;
using LibBinary.FileData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LibBinary.FileDeclaration.Binary
{
    public class Str8FieldArrangement : IFieldArrangement
    {
        public AbstractFileData Read(BinaryFileSource src, AbstractFileData parentNode, string name, IFileDeclaration decl)
        {
            if (name != ReadString(src))
            {
                throw new ReadingFormatException("Field name mismatch.");
            }
            var ret = new FieldData(parentNode);
            ret.Data = decl.Read(src, ret);
            ret.FieldName = name;
            return ret;
        }

        public void Write(BinaryFileSource src, AbstractFileData data, string name, IFileDeclaration decl)
        {
            var cdata = data.As<FieldData>();
            if (cdata == null)
            {
                throw new WritingFormatException("Wrong data type.");
            }
            if (cdata.FieldName != name)
            {
                throw new WritingFormatException("Field name mismatch.");
            }
            WriteString(src, name);
            decl.Write(src, cdata.Data);
        }

        private string ReadString(BinaryFileSource src)
        {
            var len = src.Read<byte>();

            byte[] buffer = new byte[len];
            for (int i = 0; i < len; ++i)
            {
                buffer[i] = src.Read<byte>();
            }
            return Encoding.ASCII.GetString(buffer);
        }

        private void WriteString(BinaryFileSource src, string id)
        {
            byte[] buffer = Encoding.ASCII.GetBytes(id);
            src.Write<byte>((byte)buffer.Length);
            foreach (byte b in buffer)
            {
                src.Write<byte>(b);
            }
        }

        private static Str8FieldArrangement _Instance = new Str8FieldArrangement();
        public static Str8FieldArrangement Instance
        {
            get
            {
                return _Instance;
            }
        }
    }
}
